<script lang="ts">

import {DepartmentVO, Permission, PositionVO, Result, UserBO, UserVO} from "~/api/responseResult";
import {findDepartmentAll, findPositionAll, findUserAllByUserQuery} from "~/api/warehouse";
import {arrayDeDuplication} from '~/utils'
import {QuestionFilled} from '@element-plus/icons-vue'
import {ElForm} from "element-plus";

interface PermissionState {
  tablePermission: Permission,
  administrators: Array<UserVO>,
  ordinaryUser: Array<UserVO>,
  departmentList: Array<DepartmentVO>,
  positionList: Array<PositionVO>,
}

export default defineComponent({
  name: 'SetPermission',
  props: {
    permission: {
      type: Object,
      default: {
        administrators: [],
        ordinaryUsers: [],
        departmentAndPosition: false,
        departments: [],
        positions: [],
      }
    },
    administrators: {
      type: Array,
      default: []
    },
    ordinaryUser: {
      type: Array,
      default: []
    },
  },
  components: {QuestionFilled},
  setup(props) {
    const cascadeProps = {
      multiple: true,
      checkStrictly: true,
      value: 'departmentCd',
      label: 'departmentName',
      children: 'departmentList',
      emitPath: false,

    }


    const state: PermissionState = reactive({
      tablePermission: {
        administrators: [],
        ordinaryUsers: [],
        departmentAndPosition: false,
        departments: [],
        positions: []
      },
      administrators: [],
      ordinaryUser: [],
      departmentList: [],
      positionList: [],
    })

    const rules = reactive({
      administrators: [
        {
          required: true,
          message: '请选择管理员',
          trigger: 'change',
        }
      ],
    })

    const loading = ref(false)
    const formRef = ref<InstanceType<typeof ElForm>>();

    const remoteMethod = async (query: string, identity: string) => {
      if (query) {
        loading.value = true
        let userQuery = {hrNo: query}
        const res: Result<Array<UserVO>> = await findUserAllByUserQuery(userQuery)
        if (res.success) {
          if (identity === 'administrator') {
            let list = res.data
            list.forEach(item => {
              if (state.tablePermission.ordinaryUsers.indexOf(item.userId) >= 0) {
                list = []
              }
            })
            let userList = state.administrators.concat(list)
            arrayDeDuplication(userList, 'userId')
            state.administrators = userList
          } else {
            let list = res.data
            list.forEach(item => {
              if (state.tablePermission.administrators.indexOf(item.userId) >= 0) {
                list = []
              }
            })
            let userList = state.ordinaryUser.concat(list)
            arrayDeDuplication(userList, 'userId')
            state.ordinaryUser = userList
          }
        }
        loading.value = false
      }
    }

    const getDepartmentAll = async () => {
      const res: Result<DepartmentVO> = await findDepartmentAll()
      if (res.success) {
        state.departmentList = [res.data]
      }
    }


    const getPositionAll = async () => {
      const res: Result<Array<PositionVO>> = await findPositionAll()
      if (res.success) {
        state.positionList = res.data
      }
    }

    const getPermission = (verification: boolean) => {
      let formEl: InstanceType<typeof ElForm> | undefined = formRef.value
      let result = null
      if (verification) {
        if (formEl) {
          formEl.validate((valide: any) => {
            // 只有校验通过，才执行函数
            if (valide) {
              result = {
                permission: state.tablePermission,
                administrators: state.administrators,
                ordinaryUser: state.ordinaryUser
              }
            } else {
              console.log("校验失败")
            }
          })
        }
      } else {
        result = {
          permission: state.tablePermission,
          administrators: state.administrators,
          ordinaryUser: state.ordinaryUser
        }
      }
      return result
    }

    const initTablePermission = () => {
      state.tablePermission = props.permission as Permission
      state.administrators = props.administrators as Array<UserVO>
      if (state.administrators.length == 0) {
        // 追加创建人为管理员
        const userInfo: UserBO = JSON.parse(<string>localStorage.getItem("user"))
        remoteMethod(userInfo.hrCode, 'administrator')
        state.tablePermission.administrators.push(userInfo.userPid)
      }
      state.ordinaryUser = props.ordinaryUser as Array<UserVO>
    }

    const removeTag = (val: string, identity: string) => {
      if (identity === 'administrator') {
        let administrators = state.administrators
        for (let i = 0; i < administrators.length; i++) {
          if (administrators[i].userId === val) {
            // 移除
            administrators.splice(i, 1)
          }
        }
        state.administrators = administrators
      } else {
        let ordinaryUser = state.ordinaryUser
        for (let i = 0; i < ordinaryUser.length; i++) {
          if (ordinaryUser[i].userId === val) {
            // 移除
            ordinaryUser.splice(i, 1)
          }
        }
        state.ordinaryUser = ordinaryUser
      }

    }

    onMounted(() => {
      initTablePermission()
      getDepartmentAll()
      getPositionAll()
    })

    watch(() => state.tablePermission.departments, (newValue, oldValue) => {
      if (newValue.length === 0) {
        state.tablePermission.positions = []
      }
    })

    watch(() => state.tablePermission.departmentAndPosition, (newValue, oldValue) => {
      if (!newValue) {
        state.tablePermission.departments = []
        state.tablePermission.positions = []
      }
    })

    return {
      cascadeProps,
      state,
      loading,
      remoteMethod,
      getPermission,
      formRef,
      rules,
      removeTag
    }
  }
})
</script>

<template>
  <div>
    <el-form
        :rules="rules"
        ref="formRef"
        label-width="120px"
        class="demo-ruleForm"
        :model="state.tablePermission"
    >
      <el-form-item required label="管理员" prop="administrators">
        <el-select
            v-model="state.tablePermission.administrators"
            @remove-tag="(val) => removeTag(val, 'administrator')"
            style="width: 100%;"
            multiple
            filterable
            remote
            reserve-keyword
            :remote-method="(query: string) => remoteMethod(query, 'administrator')"
            :loading="loading"
            placeholder="管理员">
          <el-option
              v-for="userVO in state.administrators"
              :key="userVO.userId"
              :label="userVO.userLabel"
              :value="userVO.userId"/>
        </el-select>
      </el-form-item>


      <el-form-item label="普通用户">
        <el-select
            v-model="state.tablePermission.ordinaryUsers"
            @remove-tag="(val) => removeTag(val, 'ordinaryUser')"
            style="width: 100%;"
            multiple
            filterable
            remote
            reserve-keyword
            :remote-method="(query: string) => remoteMethod(query, 'ordinaryUser')"
            :loading="loading"
            placeholder="普通用户">
          <el-option
              v-for="userVO in state.ordinaryUser"
              :key="userVO.userId"
              :label="userVO.userLabel"
              :value="userVO.userId"/>
        </el-select>
      </el-form-item>

      <el-form-item label="指定部门/岗位（勾选后，选项为空时表示无限制）">
        <template #label>
          <span>指定部门/岗位</span>
          <el-icon>
            <QuestionFilled/>
          </el-icon>
        </template>
        <el-switch v-model="state.tablePermission.departmentAndPosition"></el-switch>
      </el-form-item>

      <el-form-item v-if="state.tablePermission.departmentAndPosition" label="部门">
        <el-cascader style="width: 100%;" v-model="state.tablePermission.departments" :options="state.departmentList"
                     :props="cascadeProps"
                     clearable/>
      </el-form-item>

      <el-form-item
          v-if="state.tablePermission.departmentAndPosition" label="且岗位">
        <el-select
            :disabled="state.tablePermission.departments.length == 0"
            v-model="state.tablePermission.positions" style="width: 100%;"
            multiple
            filterable
            placeholder="岗位">
          <el-option
              v-for="positionVO in state.positionList"
              :key="positionVO.positionId"
              :label="positionVO.positionName"
              :value="positionVO.positionId"/>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>

</style>
